package com.block.merchant.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.ChannelBaseInfo;
import com.block.db.entity.MerchantDataPushFlowCountInfo;
import com.block.db.mapper.MerchantDataPushFlowCountInfoMapper;
import com.block.common.model.dto.FlowCountDTO;
import com.block.merchant.service.IMerchantDataPushFlowCountInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商户推送数据流量类型统计 服务实现类
 * </p>
 *
 * @author 
 * @since 2024-10-29
 */
@Service
public class MerchantDataPushFlowCountInfoServiceImpl extends ServiceImpl<MerchantDataPushFlowCountInfoMapper, MerchantDataPushFlowCountInfo> implements IMerchantDataPushFlowCountInfoService {

    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    NotifyExceptionService notifyExceptionService;
    @Autowired
    RedisTemplate<String, FlowCountDTO> redisTemplate;

    /**
     *
     */
    @Async
    @Override
    @Transactional
    public void updateFlowCount(FlowCountDTO flowCountDTO) {
        try {
            if (ObjectUtil.isEmpty(flowCountDTO.getFlowType())){
                ChannelBaseInfo channelBaseInfo = channelCommonService.getBaseInfoByCode(flowCountDTO.getChannelCode());
                flowCountDTO.setFlowType(channelBaseInfo.getFlowRateType());
            }

            MerchantDataPushFlowCountInfo dataPushFlowCountInfo = this.baseMapper.getEntityByInfoIdAndDateInfo(flowCountDTO.getInfoId());
            if (ObjectUtil.isEmpty(dataPushFlowCountInfo)) {
                dataPushFlowCountInfo = new MerchantDataPushFlowCountInfo();
                dataPushFlowCountInfo.setInfoId(flowCountDTO.getInfoId());
                dataPushFlowCountInfo.setInfoName(flowCountDTO.getInfoName());

                dataPushFlowCountInfo.setAppNumber(flowCountDTO.getAppNumber());
                dataPushFlowCountInfo.setH5Number(flowCountDTO.getH5Number());
                dataPushFlowCountInfo.setApisNumber(flowCountDTO.getApisNumber());
                dataPushFlowCountInfo.setApibNumber(flowCountDTO.getApibNumber());

                boolean insert = this.save(dataPushFlowCountInfo);
                if (!insert) {
                    throw new RuntimeException("保存商户推送流量类型统计信息失败：" + JSON.toJSONString(dataPushFlowCountInfo));
                }
                dataPushFlowCountInfo = this.baseMapper.getEntityByInfoIdAndDateInfo(flowCountDTO.getInfoId());
            }

            MerchantDataPushFlowCountInfo updateEntity = this.getUpdateCountInfo(flowCountDTO, dataPushFlowCountInfo);
            updateEntity.setId(dataPushFlowCountInfo.getId());
            this.updateById(updateEntity);

            // 更新，缓存信息
            FlowCountDTO cacheCountDTO = new FlowCountDTO();
            cacheCountDTO.setInfoId(flowCountDTO.getInfoId());
            cacheCountDTO.setAppNumber(ObjectUtil.isEmpty(updateEntity.getAppNumber())?dataPushFlowCountInfo.getAppNumber():updateEntity.getAppNumber());
            cacheCountDTO.setH5Number(ObjectUtil.isEmpty(updateEntity.getH5Number())?dataPushFlowCountInfo.getH5Number():updateEntity.getH5Number());
            cacheCountDTO.setApibNumber(ObjectUtil.isEmpty(updateEntity.getApibNumber())?dataPushFlowCountInfo.getApibNumber():updateEntity.getApibNumber());
            cacheCountDTO.setApisNumber(ObjectUtil.isEmpty(updateEntity.getApisNumber())?dataPushFlowCountInfo.getApisNumber():updateEntity.getApisNumber());

            String redisKey = StrUtil.format(RedisKeyConstant.DATA_PUSH_FLOW_COUNT_KEY, flowCountDTO.getInfoId());
            redisTemplate.opsForValue().set(redisKey, cacheCountDTO, 3, TimeUnit.DAYS);
        } catch (Exception exception) {
            exception.printStackTrace();
            notifyExceptionService.notifyNoticeInfo("DATA_PUSH_FLOW_COUNT", "商户推送流量类型统计异常", JSON.toJSONString(flowCountDTO), exception);
        }
    }

    private MerchantDataPushFlowCountInfo getUpdateCountInfo(FlowCountDTO countInfoDTO, MerchantDataPushFlowCountInfo channelCountInfo) {

        MerchantDataPushFlowCountInfo updateEntity = new MerchantDataPushFlowCountInfo();

        if (ObjectUtil.isNotEmpty(countInfoDTO.getAppNumber())) {
            updateEntity.setAppNumber(channelCountInfo.getAppNumber() + countInfoDTO.getAppNumber());
        }

        if (ObjectUtil.isNotEmpty(countInfoDTO.getH5Number())) {
            updateEntity.setH5Number(channelCountInfo.getH5Number() + countInfoDTO.getH5Number());
        }

        if (ObjectUtil.isNotEmpty(countInfoDTO.getApibNumber())) {
            updateEntity.setApibNumber(channelCountInfo.getApibNumber() + countInfoDTO.getApibNumber());
        }

        if (ObjectUtil.isNotEmpty(countInfoDTO.getApisNumber())) {
            updateEntity.setApisNumber(channelCountInfo.getApisNumber() + countInfoDTO.getApisNumber());
        }

        return updateEntity;
    }
}
